package com.stone.mythread;

/**
 * 创建多线程的方式二：实现 Runnable 接口
 * 1. 创建一个实现了 Runnable 接口的类
 * 2. 实现类去实现 Runnable 中的抽象方法： run()
 * 3. 创建实现类的对象
 * 4. 将此对象作为参数传递到 Thread 类的构造器中，创建 Thread 类的对象
 * 5. 通过 Thread 类的对象调用 start()
 */
public class ThreadRunable implements Runnable {

    private int ticket = 100;

    @Override
    public void run() {
        while (true) {
            show();
        }
    }

    private synchronized void show() { // 同步监视器：默认为 this
        if (ticket > 0) {
            System.err.println(Thread.currentThread().getName() + "：卖票，票号为：" + ticket);
            ticket--;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadRunable test = new ThreadRunable();
        Thread thread1 = new Thread(test);
        thread1.setName("窗口一");
        thread1.start();
        Thread thread2 = new Thread(test);
        thread2.setName("窗口二");
        thread2.start();
        Thread thread3 = new Thread(test);
        thread3.setName("窗口三");
        thread3.start();
    }
}
